<template>
    <div class="filter-wrap" @click="showFilterBox">
        <el-popover width="250" popper-class="filter-pop" v-model:visible="visible" @after-leave="resumeFilterValueOnLeave">
            <template #reference>
                <span class="text" :class="{actived:hasFilter}">
                    <el-tooltip placement="top" :content="getFilterTitle()" :disabled="!hasFilter">
                        <div class="no-outline">
                            <slot></slot>
                            <i class="el-icon-caret-bottom filter-icon" ></i>
                        </div>
                    </el-tooltip>
                </span>
            </template>
            
            <div class="filter-pop-wrap">
                <!-- text 文本输入 -->
                <div v-if="type=='text'">
                    <el-input width="100" size="mini" class="text-input" v-model="filterValue" ref="textInputElm">
                        <template #append>
                            <el-button title="清空" size="mini" icon="el-icon-close" class="x-btn border-right filter-btn" @click="cleanFilter"></el-button>
                            <el-button size="mini" type="primary" @click="onchange" class="filter-btn">{{$tic('btn.filter', '筛选')}}</el-button>
                        </template>
                    </el-input>
                </div>
    
                <!-- checkbox, radio -->
                <div v-else-if="['checkbox', 'radio'].includes(type)">
                    <div class="search">
                        <el-input width="100" size="mini" class="text-input" v-model="optionSearchWord">
                            <template #append>
                                <el-button title="清空" size="mini" icon="el-icon-close" @click="resetSearchKeyword" class="x-btn filter-btn"></el-button>
                            </template>
                        </el-input>
                    </div>
                    <div class="search-body">
                        <ul>
                            <li v-for="row in filterSearchOptions">
                                <el-checkbox-group v-model="filterValue" v-if="type == 'checkbox'">
                                    <el-checkbox :label="row.value" :title="row.text">{{row.text}}</el-checkbox>
                                </el-checkbox-group>
                                <el-radio-group v-model="filterValue" v-else-if="type == 'radio'">
                                    <el-radio :label="row.value" :title="row.text">{{row.text}}</el-radio>
                                </el-radio-group>
                            </li>
                        </ul>
                    </div>
                    <div class="btns" v-if="filterSearchOptions.length">
                        <el-button size="mini" @click="cleanFilter" v-if="clearable">{{$tic('btn.clean', '清空')}}</el-button>
                        <el-button size="mini" @click="visible=false">{{$tic('btn.cancel', '取消')}}</el-button>
                        <el-button size="mini" type="primary" @click="onchange">{{$tic('btn.filter', '筛选')}}</el-button>
                    </div>
                </div>
    
                <!-- date 日期类型 -->
                <div v-else-if="'date' == type">
                    <el-date-picker v-model="filterValue" :type="dateType"
                                    :start-placeholder="$tic('common.startTime', dateStartPlaceholder)"
                                    :end-placeholder="$tic('common.endTime', dateEndPlaceholder)"
                                    :clearable="clearable"
                    ></el-date-picker>
                    <div class="btns">
                        <el-button size="mini" @click="cleanFilter" v-if="clearable">{{$tic('btn.clean', '清空')}}</el-button>
                        <el-button size="mini" @click="visible=false">{{$tic('btn.cancel', '取消')}}</el-button>
                        <el-button size="mini" type="primary" @click="onchange">{{$tic('btn.filter', '筛选')}}</el-button>
                    </div>
                </div>
            </div>
        </el-popover>
    </div>
</template>

<script>
    const {loadComponentGroupByName} = $byview;
    const {getCurrentInstance, toRef, h, ref, watch, reactive, computed} = Vue;
    
    let components = await loadComponentGroupByName(['byview/components/base/help.vue']);
    const ARYTYPE = Object.prototype.toString.call([]);
    
    export default {
        components,
        name:"ByColumnFilter",
        props: {
            sortable: {
                default: null
            },
            
            modelValue: {
                default: ''
            },
            
            defaultValue: {
                default:''
            },
            
            type: {
                default: "text"
            },
            
            name: {
                default: ''
            },
            
            filterOptions: {
                default:[]
            },

            dateType: {
                default: "datetimerange"
            },

            clearable: {
                default: true,
            },

            dateStartPlaceholder: {
                default: "开始时间",
            },

            dateEndPlaceholder: {
                default: "结束时间",
            },
            
            defaultFiltered: {
                default: ''
            }
        },
        
        setup(props, context) {
            let {ctx} = getCurrentInstance();
            let {type} = props;
            
            //筛选列表项
            let filterSearchOptions = ref([]);
            //筛选选中的值
            let filterValue=ref('');
            //搜索关键字
            let optionSearchWord = ref('');
            let filtered = ref('');
            let visible = ref(false);
            
            let _isAryResult = ["checkbox", "date"].includes(type);
    
            // if(props.defaultValue || props.defaultValue === 0) {
            //     filterValue.value = props.defaultValue;
            //     filtered.value = props.defaultValue;
            // }
            
            filterValue.value = props.modelValue;
            filtered.value = filterValue.value;
    
            if(_isAryResult) {
                filterValue.value = (filterValue.value instanceof Array) ? filterValue.value : [];
            }
            
            if(props.defaultFiltered) {
                filterValue.value = props.defaultFiltered;
            }
            
            watch(
                _ => props.modelValue,
                v => {
                    filterValue.value = v;
                }
            );
            
            //搜索选项
            let search = keyword => {
                let result = [];
                let isAry = ARYTYPE == Object.prototype.toString.call(props.filterOptions);
                
                for(let key in props.filterOptions) {
                    let option = props.filterOptions[key];
                    
                    if(typeof option == 'string') {
                        if(isAry) {
                            option = {value:option};
                        } else {
                            option = {value:key, text:option};
                        }
                    }

                    if(!option.text && option.text != '0') {
                        option.text = option.value;
                    }

                    if(!keyword && keyword != '0') {
                        result.push(option);
                        continue;
                    }

                    let pos = option.text.toLowerCase().indexOf(keyword.toLowerCase());

                    if(pos >= 0) {
                        result.push(option);
                    }
                }

                return result;
            };
            
            let searchTimer = null;
            let searchDelay = () => {
                clearTimeout(searchTimer);
                searchTimer = setTimeout(_ => filterSearchOptions.value = search(optionSearchWord.value), 300);
            };

            let resetSearchKeyword = _ => {
                optionSearchWord.value = '';
                searchDelay();
            };

            if(['checkbox', 'radio'].includes(type)) {
                filterSearchOptions.value = search(optionSearchWord.value);

                watch(optionSearchWord, _ => {
                    searchDelay();
                });
            }

            
            let onchange = function () {
                let value = filterValue.value;
                
                if(typeof value == 'object' && typeof value.length != 'undefined') {
                    value = Array.prototype.slice.call(value);
                }
                
                visible.value = false;
                filtered.value = value;
                context.emit('update:modelValue', value);
                context.emit('change', {name: props.name, value});
            };
            
            //input输入框
            let textInputElm = ref(null);
            
            /**
             * 清空筛选
             */
            let cleanFilter = _ => {
                console.log(ctx);
                if(_isAryResult) {
                    filterValue.value = [];
                    onchange();
                } else {
                    filterValue.value = '';
                    textInputElm.value && textInputElm.value.focus();
                }
            };
            
            /**
             * 判断是否正在筛选
             */
            let hasFilter = computed(_ => {
                let value = filtered.value || filterValue.value;
                
                if(!value) {
                    return false;
                }
                
                if(typeof value.length != 'undefined') {
                    return value.length > 0;
                }
               
                return !!value;
            });

            /**
             * 没有筛选关闭筛选框后重置原筛选数据
             */
            let resumeFilterValueOnLeave = () => {
                if(filterValue.value != filtered.value) {
                    filterValue.value = filtered.value;
                }
            };
            
            let getFilterTitle = () => {
                if(_isAryResult) {
                    if(props.type == 'date') {
                        if(props.dateType == 'daterange') {
                            return dayjs(filtered.value[0]).format('YYYY-MM-DD') + ' ~ ' + dayjs(filtered.value[1]).format('YYYY-MM-DD');
                        } else {
                            return dayjs(filtered.value[0]).format('YYYY-MM-DD HH:mm:ss') + ' ~ ' + dayjs(filtered.value[1]).format('YYYY-MM-DD HH:mm:ss');
                        }
                    } else {
                        return ARYTYPE == Object.prototype.toString.call(filtered.value) ? filtered.value.join(',') : '';
                    }
                } else {
                    return filtered.value;
                }
            };
            
            let showFilterBox = () => {
                console.log('adsdd');
                visible.value = true;
            };
            
            return {
                optionSearchWord,
                filterSearchOptions,
                filterValue,
                resetSearchKeyword,
                searchDelay,
                search,
                
                visible,
                onchange,
                cleanFilter,
                hasFilter,

                resumeFilterValueOnLeave,
                textInputElm,

                getFilterTitle,
                showFilterBox,
            }
        }
    }
</script>

<style scoped>
    .filter-wrap {
        width: 100%;
        height: 100%;
        padding-right: 15px;
        position: relative;
        box-sizing: border-box;
    }
    .filter-btn {
        margin:0;
    }
    
    .btns {
        padding-top:10px;
    }
    
    .text-input {
        height:32px;
    }
    
    .text-input input {
        height:32px;
    }
    
    .x-btn {
        border-radius: 0;
    }
    
    .border-right {
        border-right:solid 1px #e8e5e5 !important;
    }
    
    .text {
        cursor:pointer;
    }
    
    .text i {
        font-size:12px;
        transform: scale(.75);
    }
    
    .text.actived,
    .text.actived i {
        color:#FF6666;
    }
    
    .search-body {
        max-height: 300px;
        max-width: 350px;
        overflow-x: hidden;
        overflow-y: scroll;
        margin-top:10px;
    }
    
    .search-body ul li {
        padding: 3px 0;
    }

    .search-body ul li .el-checkbox:hover,
    .search-body ul li .el-radio:hover
    {
        color:#4169E1;
    }
    
    i.filter-icon {
        font-size: 16px;
        font-weight: bold;
    }
    
    .filter-pop-wrap/*/scoped/*/ .text-input .el-input-group__append {
        padding: 0;
    }

    .no-outline {
        outline:0;
    }
</style>
